package com.club.football.utils;

import cn.hutool.core.text.StrPool;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.club.football.common.BusinessException;
import lombok.SneakyThrows;
import org.springframework.util.DigestUtils;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.URL;
import java.net.URLDecoder;

import static com.club.football.common.CommonConstants.*;


/**
 * 文件Utils
 *
 * @author 1
 * @date 2024/01/22
 */
public class FileUtils {
    private FileUtils() {
    }

    @SneakyThrows
    public static String getDirPath() {
        URL url = FileUtils.class.getClassLoader().getResource("");
        if (url == null) {
            return null;
        }
        try {
            File file = new File(url.getFile() + "/WEB-INF/static");
            if (!file.exists()) {
                //创建文件夹
                boolean mkdir = file.mkdir();
                if (mkdir) {
                    throw new BusinessException("创建文件夹失败");
                }
            }
            return URLDecoder.decode(url.getFile() + "WEB-INF/static", "utf8");
        } catch (UnsupportedEncodingException e) {
            return url.getFile();
        }
    }

    /**
     * 获取图像URL
     *
     * @param fileName 文件名文件名
     * @return {@link String}
     */
    public static String getImageUrl(String fileName) {
        return StrPool.SLASH + FILE_LOCAL + StrPool.SLASH + fileName;
    }

    /**
     * 跳转至
     *
     * @param baseUrl 基本URL
     * @return {@link String}
     */
    @SneakyThrows
    public static String getUrl(String baseUrl) {
        if (StringUtils.isBlank(baseUrl)) {
            return null;
        }
        if (baseUrl.contains(HTTP_HEAD)) {
            return baseUrl;
        }
        InetAddress addr = InetAddress.getLocalHost();
        return HTTP_HEAD + addr.getHostAddress() + StrPool.COLON + BASE_PORT + baseUrl;
    }

    /**
     * 到MD5
     *
     * @param pwd PWD
     * @return {@link String}
     */
    public static String toMd5(String pwd) {
        return DigestUtils.md5DigestAsHex(pwd.getBytes());
    }
}
